package com.tidc.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tidc.manage.domain.Role;
import com.tidc.manage.domain.UserRole;
import com.tidc.manage.mapper.RoleMapper;
import com.tidc.manage.mapper.UserRoleMapper;
import com.tidc.manage.service.IUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张朝锋
 * @author 张伟杰
 * @since 2018-09-14
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public int getRoleLevelByUserId(String userId) {
        UserRole userRole = baseMapper.selectOne(new QueryWrapper<UserRole>().eq("user_id", userId));
        Role role = roleMapper.selectById(userRole.getRoleId());
        return role.getLevel();
    }

    @Override
    public IPage<UserRole> getUserRoleOfPage(long current, long size, int level) {
        return baseMapper.getUserRoleOfPage(new Page<>(current, size), level);
    }

    @Override
    public Integer updateUserRoleByUserId(UserRole userRole) throws NotFoundException {
        UserRole oldUserRole = baseMapper.selectOne(
                new QueryWrapper<UserRole>().eq("user_id", userRole.getUserId()));
        if (oldUserRole == null) {
            throw new NotFoundException("UserId(" + userRole.getUserId() + ")");
        }
        oldUserRole.setRoleId(userRole.getRoleId());
        return oldUserRole.updateById() ? 1 : 0;
    }

    @Override
    public void initializeUserRoleForStudentByStudentId(String studentId) {
        UserRole userRole = new UserRole();
        userRole.setUserId(studentId);
        userRole.setRoleId(DEFAULT_USER_LEVEL);
        baseMapper.insert(new UserRole());
    }

    @Override
    public void deleteUserRoleByUserId(String userId) throws NotFoundException {
        if (baseMapper.selectOne(new QueryWrapper<UserRole>()
                .eq("user_id", userId)) == null) {
            throw new NotFoundException("UserRole'user_id(" + userId + ")");
        }
        baseMapper.delete(new QueryWrapper<UserRole>().eq("user_id", userId));
    }
}
